import store from './index'

//初始化websocket


//将初始化socket函数、发送（接收）数据的函数、关闭连接的函数export出去
export default {
    state: {
        webSocket: null,
        // globalCallback: null,//定义外部接收数据的回调函数
    },
    mutations: {
        initWebSocket(state, url) {
            if ("WebSocket" in window) {
                if (url == '') {
                    alert("请输入正确的服务器地址")
                    return
                }
                state.webSocket = new WebSocket(`ws://${url}`);//创建socket对象
                //打开
                console.log(state.webSocket)
                state.webSocket.onopen = function () {
                    state.webSocket.send(JSON.stringify({ command: 1 }))
                };
                //收信
                state.webSocket.onmessage = function (e) {
                    store.commit('setStatus', JSON.parse(e.data))
                };
                //关闭
                state.webSocket.onclose = function () {
                    state.webSocket.close();//这句话是关键，之前我忘了写，一直没有真正的关闭socket
                    state.webSocket = null;
                };
                //连接发生错误的回调方法
                state.webSocket.onerror = function (e) {
                    alert("连接错误")
                    console.log(e, "WebSocket连接发生错误");
                };
            } else {
                alert("该浏览器不支持websocket!");
            }

        },
    },
};